require("zlib_b64")

-- Round a number to the nearest 'val' - e.g. 10.61 to the nearest 0.5 = 10.5.
function math.RoundTo(x, val)
	local y = x % val
	return ((y < (val / 2)) and (x - y) or (x + (val - y)))
end

function TestZlib(f, complevel, strategy)
	local data = file.Read(f)
	if not data then error("Unable to read file \""..f.."\" - "..(file.Exists(f) and "Access is denied." or "The system cannot find the file specified.").."\n") end
	print("\""..f.."\"")
	
	-- Compression
	local cmp = zlib.Compress(data, complevel, strategy)
	-- Compression ratio and size rounded to 2 decimal places.
	print("\tCompressed (level "..(complevel or 6)..") to "..math.RoundTo(#cmp / 1024, 0.01).."KB from "..math.RoundTo(cmp:UncompressedSize() / 1024, 0.01).."KB (compression ratio: "..math.RoundTo(100 - ((#cmp / datalen) * 100), 0.01).."%)")
	
	-- Write to file
	cmp:Write("temp.z")
	print("\tCompressed data written to \"temp.z\"")
	
	-- Read from file
	local cmpread = zlib.Read("temp.z")
	print("\tData read from file \"temp.z\", "..((cmp == cmpread) and "matches" or "does not match").." original compressed data.")
	file.Delete("temp.z")
	
	
	
	-- Encoding
	local enc = cmp:Encode()
	print("\tBase64 encoded ("..math.RoundTo(enc:len() / 1024, 0.01).."KB)")
	
	-- Decoding
	local cmp2 = b64.Decode(enc)
	print("\tBase64 decoded. Decoded data "..((cmp == cmp2) and "matches" or "does not match").." compressed data")
	
	-- Decompression
	local data2 = cmp:Decompress()
	print("\tDecompressed. Decompressed data "..((data == data2) and "matches" or "does not match").." original data")
	
	return ((cmp == cmp2) && (data == data2) && (cmp == cmpread)), #cmp, cmp:UncompressedSize
end